package cn.iocoder.yudao.module.member.controller.app.user;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.*;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.group.MemberGroupDO;
import cn.iocoder.yudao.module.member.dal.dataobject.level.MemberLevelDO;
import cn.iocoder.yudao.module.member.dal.dataobject.tag.MemberTagDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.level.MemberLevelService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.websocket.server.PathParam;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 用户个人中心")
@RestController
@RequestMapping("/member/user")
@Validated
@Slf4j
public class AppMemberUserController {

    @Resource
    private MemberUserService userService;
    @Resource
    private MemberLevelService levelService;

    @GetMapping("/get")
    @Operation(summary = "获得基本信息")
    @PreAuthenticated
    public CommonResult<MemberUserDO> getUserInfo() {
        MemberUserDO user = userService.getUser(getLoginUserId());
        MemberLevelDO level = levelService.getLevel(user.getLevelId());
        return success(user);
    }

    @GetMapping("/getById")
    @Operation(summary = "获得基本信息")
    @PreAuthenticated
    public CommonResult<MemberUserDO> getUserInfo(@RequestParam("id") Long id) {
        MemberUserDO user = userService.getUser(id);
        MemberLevelDO level = levelService.getLevel(user.getLevelId());
        return success(user);
    }

    @GetMapping("/getByReferrer")
    @Operation(summary = "获得基本信息")
    @PreAuthenticated
    public CommonResult<MemberUserDO> getByReferrer(@RequestParam("referrer") String referrer) {
        MemberUserDO user = userService.getUserByReferrer(referrer);
        return success(user);
    }

    @PutMapping("/update")
    @Operation(summary = "修改基本信息")
    @PreAuthenticated
    public CommonResult<Boolean> updateUser(@RequestBody @Valid AppMemberUserUpdateReqVO reqVO) {
        userService.updateUser(reqVO.getId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-mobile")
    @Operation(summary = "修改用户手机")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserMobile(@RequestBody @Valid AppMemberUserUpdateMobileReqVO reqVO) {
        userService.updateUserMobile(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "修改用户密码", description = "用户修改密码时使用")
    @PreAuthenticated
    public CommonResult<Boolean> updatePassword(@RequestBody AppMemberUserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/reset-password")
    @Operation(summary = "重置密码", description = "用户忘记密码时使用")
    public CommonResult<Boolean> resetPassword(@RequestBody @Valid AppMemberUserResetPasswordReqVO reqVO) {
        userService.resetUserPassword(reqVO);
        return success(true);
    }

    @PostMapping("/register")
    @Operation(summary = "注册", description = "注册新用户")
    public CommonResult<Boolean> register(@RequestBody AppMemberUserResetPasswordReqVO reqVO) {
//        MemberUserDO memberUserDO = userService.getUserByReferrer(reqVO.getCode());
//        if (null == memberUserDO) {
//            return error(4042, "推荐码错误，找不到此用户！");
//        }

        userService.createUserByPwd(reqVO.getMobile(), reqVO.getPassword(), reqVO.getCode(), reqVO.getName());
        return success(true);
    }

    @PostMapping("/pay/password")
    @Operation(summary = "注册", description = "注册新用户")
    public CommonResult<Boolean> setPayPassword(@RequestBody AppMemberUserUpdateReqVO reqVO) {
        userService.updatePayPassword(reqVO);
        return success(true);
    }

    @GetMapping("/referrer-count")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<List<MemberUserDO>> referrerCount(@RequestParam("id") Long id) {
        MemberUserDO memberUserDO = userService.getUser(id);
        if (null != memberUserDO && null != memberUserDO.getCode()) {
            return success(userService.getReferrerByUserCode(memberUserDO.getCode()));
        } else {
            return success(new ArrayList<>());
        }
    }

    @GetMapping("/getReferrerByUserId")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<List<MemberUserDO>> getReferrerByUserId(@RequestParam("id") Long id) {
        return success(userService.getReferrerByUserId(id));
    }

    @GetMapping("/all-referrer-count")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<List<MemberUserDO>> allReferrerCount(@RequestParam("id") Long id) {
        return success(userService.getAllReferrerByUserId(id));
    }

    @GetMapping("/whetherCanBeUpgraded")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<List<MemberUserDO>> whetherCanBeUpgraded(MemberUserPageReqVO memberUserPageReqVO) {
        if (memberUserPageReqVO.getLevelId().equals(0L)) {
            memberUserPageReqVO.setExperience(60);
        }
        return success(userService.whetherCanBeUpgraded(memberUserPageReqVO));
    }

    @GetMapping("/register/sum")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<Map<String, Object>> registerSum(@RequestParam("code") String code) {
        Map<String, Object> sumP = new HashMap<>();
        sumP.put("f_reg_sum_p", userService.betSum(code, 1).get("sum_p"));
        sumP.put("s_reg_sum_p", userService.betSum(code, 2).get("sum_p"));
        return success(sumP);
    }

    @GetMapping("/all/sum")
    @Operation(summary = "获取团队数量", description = "获取团队数量")
    public CommonResult<List<Map<String, Object>>> allSum(@RequestParam("code") String code) {
        return success(userService.allSum(code));
    }

    @GetMapping("/recharge/sum")
    @Operation(summary = "下级充值统计", description = "下级充值统计")
    public CommonResult<List<Map<String, Object>>> rechargeSum(@RequestParam("code") String code,
                                                               @RequestParam(name="startTime",required = false) String startTimeStr,
                                                               @RequestParam(name="endTime",required = false) String endTimeStr) {

        // 当前时间
        LocalDate date = LocalDate.now();
        LocalDate StartTime = StrUtil.isNotBlank(startTimeStr)? LocalDate.parse(startTimeStr) : date.minusDays(30) ;
        LocalDate EndTime = StrUtil.isNotBlank(endTimeStr)? LocalDate.parse(endTimeStr) :  date ;

        List<Map<String, Object>> result = userService.rechargeSum(code,StartTime,EndTime) ;


//        "level_1_sum": 0,
//                "code": "eIwC",
//                "last_time": "0",
//                "id": 419

        for (int i = 0, n = result.size(); i < n; i++) {
            Map<String, Object> item = result.get(i) ;
            String id = item.get("id").toString() ;
            String recharge_code = item.get("code").toString() ;

            List<Map<String, Object>> child_1 = userService.rechargeSum(recharge_code,StartTime,EndTime) ;

            item.put("level_2_count",child_1.size()) ;
            // 三级人数
            int level_3_count = 0 ;
            BigDecimal level_2_sum = new BigDecimal(0);
            BigDecimal level_3_sum = new BigDecimal(0);

            for (int j = 0, child_1_n = child_1.size(); j < child_1_n; j++) {

                Map<String, Object> child_1_item = child_1.get(i) ;
                level_2_sum.add(((BigDecimal) child_1_item.get("level_1_sum"))) ;

                String level_2_code = child_1_item.get("code").toString() ;
                List<Map<String, Object>> child_2 = userService.rechargeSum(level_2_code,StartTime,EndTime) ;

                for (int k = 0, child_2_n = child_2.size(); k < child_1_n; k++) {
                    level_3_count++ ;

                    Map<String, Object> child_2_item = child_2.get(i) ;
                    level_3_sum.add(((BigDecimal) child_2_item.get("level_1_sum"))) ;
                }


            }



            item.put("level_3_count",level_3_count) ;
            item.put("level_3_sum",level_3_sum) ;
            item.put("level_2_sum",level_2_sum) ;
        }




        return success(result);
    }



}

